<?
require_once(dirname(__FILE__).'/../models/Languages.php');
require_once(dirname(__FILE__).'/../models/LocaleSections.php');
require_once(dirname(__FILE__).'/../models/LocaleDefaults.php');
require_once(dirname(__FILE__).'/../models/LocaleTranslations.php');

class LocaleController extends Main_Controller_Action {	
	public function preDispatch()
    {
    	//Database::instance()->getConn()->debug=1;
        if (!unserialize(Zend_Auth::getInstance()->getIdentity())->getIsAdministrator()) {        
                $this->_helper->redirector('', '');
        } else {
           /**
			 * Translation - Loading dictionaries common and backoffice_common
			 */
			$commonLocale = Translator::loadTranslation($this->currentLang, 'common');
			$this->view->commonLocale = $commonLocale;
        }
    }
    
	function defaultsAction(){
		try{
			$filter = "";
			$orderBy = "ORDER BY section ASC";
			$sections = ModelMapper::instance('LocaleSections')->findFiltered($filter, $orderBy);
			
			
		} catch (DatabaseException $e){
			$e->getMessage();
		}
		
		$this->view->sections = $sections;
	}
	
	function addDefaultAction(){
		$this->view->languagesId = $this->config->locale->defaultLanguageId;		
		$this->view->localeSectionsId = intval($this->getRequest()->getParam('localeSectionsId'));		
		
		$smarty = $this->view->getEngine();
		$tpl = $smarty->fetch('locale/add-default.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function editDefaultAction(){
		/*debug($this->getRequest()->getParam('localeDefaultsId'));
		debug($default);*/
		$default = ModelMapper::instance('LocaleDefaults')->find(intval($this->getRequest()->getParam('localeDefaultsId')));
		
		$smarty = $this->view->getEngine();
		
		$this->view->default = $default;
		$tpl = $smarty->fetch('locale/edit-default.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function saveDefaultAction(){
		//Database::instance()->getConn()->debug=1;
		$formData = $this->_request->getParam('addForm');
		
		
		if (intval($formData['localeDefaultsId']) >0)
			$obj = ModelMapper::instance('LocaleDefaults')->find(intval($formData['localeDefaultsId']));
		else {
			$obj = new LocaleDefaults(null,null,false);
		}
			//from config
		
		try {
			$obj->setLanguagesId(intval($this->config->locale->defaultLanguageId));
			$obj->setLocaleSectionsId(intval($formData['localeSectionsId']));
			$obj->setTranslation(trim(strip_tags(stripcslashes($formData['translation']))));
				
			ObjectWatcher::flushOperations();
		} catch (DatabaseException $e){
			debug($e->getMessage());
		}
		exit();
	}
	
	function deleteDefaultAction(){
		//Database::instance()->getConn()->debug=1;
		$lSection = ModelMapper::instance('LocaleDefaults')->find(intval($this->getRequest()->getParam('localeDefaultsId')));
		$lSection->delete();

		exit();
	}
	
	function sectionDefaultsAction(){
		//Database::instance()->getConn()->debug=1;
		
		$filter = "WHERE locale_sections_id = ".$this->getRequest()->getParam('localeSectionsId')."";
		$orderBy = "ORDER BY id ASC";
		$defaults = ModelMapper::instance('LocaleDefaults')->findFiltered($filter, $orderBy);
		
		$this->view->defaults = $defaults;
		$smarty = $this->view->getEngine();

		$tpl = $smarty->fetch('locale/section-defaults.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function langTranslationsAction(){
		//Database::instance()->getConn()->debug=1;
		$languagesId = $this->getRequest()->getParam('languagesId');
		$filter = "WHERE locale_sections_id = ".$this->getRequest()->getParam('localeSectionsId')."";
		$orderBy = "";
				
		$sTranslation = ModelMapper::instance('LocaleTranslations')->getPhrasesToTranslate($languagesId, $filter, $orderBy);
			
		$this->view->sTranslation = $sTranslation;
		$this->view->languagesId = $this->getRequest()->getParam('languagesId');
		$this->view->localeSectionsId = $this->getRequest()->getParam('localeSectionsId');
		$smarty = $this->view->getEngine();

		$tpl = $smarty->fetch('locale/translate-default.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	/**
	 * LOCALIZATION SECTIONS *
	 *
	 */
	function sectionsAction(){
		try{
			$filter = "";
			$orderBy = "ORDER BY section ASC";
			$sections = ModelMapper::instance('LocaleSections')->findFiltered($filter, $orderBy);
			
			
		} catch (DatabaseException $e){
				$e->getMessage();
		}
		$this->view->sections = $sections;
	}
	
	function addSectionAction(){
		$smarty = $this->view->getEngine();

		$tpl = $smarty->fetch('locale/add-section.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function editSectionAction(){
		$section = ModelMapper::instance('LocaleSections')->find(intval($this->getRequest()->getParam('localeSectionsId')));
		
		$smarty = $this->view->getEngine();
		
		$this->view->section = $section;
		$tpl = $smarty->fetch('locale/edit-section.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function saveSectionAction(){
		$formData = $this->_request->getParam('addForm');
		
		if (intval($formData['localeSectionsId']) >0)
			$obj = ModelMapper::instance('LocaleSections')->find(intval($formData['localeSectionsId']));
		else
			$obj = new LocaleSections();
		
		$obj->setSection(trim(strip_tags(stripcslashes($formData['section']))));
		
		$str = "<script>
			closePopup();
			window.location.reload();
			</script>";
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($str);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function deleteSectionAction(){
		$lSection = ModelMapper::instance('LocaleSections')->find(intval($this->getRequest()->getParam('localeSectionsId')));
		$lSection->delete();

		exit();
	}
	/**
	 * TRANSLATION SECTION
	 */
	
	function translationsAction(){
		try{
			$filter = "";
			$orderBy = "ORDER BY section ASC";
			$sections = ModelMapper::instance('LocaleSections')->findFiltered($filter, $orderBy);
			
			
		} catch (DatabaseException $e){
				$e->getMessage();
		}
		
		$this->view->sections = $sections;
		$this->view->languagesId = $this->getRequest()->getParam('languagesId');
			
		$smarty = $this->view->getEngine();
		$tpl = $smarty->fetch('locale/translations.tpl');
		
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function addTranslationAction(){
		$smarty = $this->view->getEngine();

		$tpl = $smarty->fetch('locale/add-translation.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function editTranslationAction(){
		$translation = ModelMapper::instance('LocaleTranslations')->find(intval($this->getRequest()->getParam('localeTranslationsId')));
		
		$smarty = $this->view->getEngine();
		
		$this->view->translation = $translation;
		$tpl = $smarty->fetch('locale/edit-translation.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function saveTranslationAction(){
		//Database::instance()->getConn()->debug=1;
		$formData = $this->_request->getParam('addForm');
		
		if (sizeof($formData['translations']) > 0){
			Database::instance()->startTrans();
			foreach ($formData['translations'] as $v){
				if (trim(strip_tags(stripcslashes($v['phrase']))) != ''){
					if (!empty($v['localeTranslationsId'])){
						$obj = new LocaleTranslations($v['localeTranslationsId']);
					} else {
						$obj = new LocaleTranslations();
					}
				
					$obj->setLanguagesId($formData['languagesId']);
					$obj->setLocaleDefaultsId(intval($v['localeDefaultsId']));
					$obj->setTranslation(trim(strip_tags(stripcslashes($v['phrase']))));
					
					ObjectWatcher::flushOperations();
					//debug($obj);
				}
			}
			Database::instance()->completeTrans();
		}
		
		exit();
	}
	
	#################
	######### GENERATE LOCALE FILES
	##########################
	
	function generateDefaultsAction(){
		//Database::instance()->getConn()->debug=1;
		
		$filter = "";
		$orderBy = "ORDER BY ls_section ASC, id ASC";
		$defaults = ModelMapper::instance('LocaleDefaults')->findFiltered(null, $filter, $orderBy);
	
		/**
		 * Sorting Defaults by Sections
		 */
		$currentSection = '';
		$section = array();
		foreach ($defaults as $k=>$v){
			if ($currentSection != $v->getSection()->getSection()){
				$currentSection = $v->getSection()->getSection();
			}
			$section[$currentSection][] = $v;
		}
		
		/**
		 * Writing Defaults to files named by section
		 */
		foreach ($section as $k=>$v){
			if (substr($_SERVER['DOCUMENT_ROOT'], -1, strlen($_SERVER['DOCUMENT_ROOT'])) != DIRECTORY_SEPARATOR){
				$_SERVER['DOCUMENT_ROOT'] = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR;
			}
			$fileName = $_SERVER['DOCUMENT_ROOT'].$this->config->locale->localeDefaultsDir.'/'.$k.'.php';
			//echo $fileName;
			/*if (!file_exists($fileName)){
				$file = fopen($fileName, "w+");
				fclose($file);
			}*/
			ob_start();
			echo "<?php return array( \n";
			$i = 1;
			foreach ($v as $key => $value){
				echo "\t".'"'.$value->getTranslation().'" => "'.$value->getTranslation().'"';
				if($i < sizeof($v))
					echo ',';
				echo "\n";
				$i++;
			}
		
			echo '); ?>';
			$content = ob_get_contents();
		    ob_end_clean();
	    	
		    file_put_contents($fileName, $content);
		}
		
		$msg = "Files creation success";
		echo $msg;
		exit();
		/*$this->view->defaults = $defaults;
		$smarty = $this->view->getEngine();

		$tpl = $smarty->fetch('locale/generate-defaults.tpl');*/
		
	}
	
	function generateTranslationsAction(){
		//Database::instance()->getConn()->debug=1;
		
		//$languagesId = 2;
		$languagesId = intval($this->getRequest()->getParam('languagesId'));
		$language = ModelMapper::instance('Languages')->find($languagesId);
		
		$filter = "";
		$orderBy = "ORDER BY ls_section ASC, id";
		
		$sTranslations = ModelMapper::instance('LocaleTranslations')->getPhrasesToTranslate($languagesId, $filter, $orderBy);
		
		/**
		 * Sorting Defaults by Sections
		 */
		$currentSection = '';
		$section = array();
		foreach ($sTranslations as $k=>$v){
			
			if ($currentSection != $v['ls_section']){
				$currentSection = $v['ls_section'];
			}
			
			$section[$currentSection][] = $v;
		}
		
		/**
		 * Writing Defaults to files named by section
		 */
		foreach ($section as $k=>$v){
			
			$fileName = $_SERVER['DOCUMENT_ROOT'].'/'.$this->config->locale->localeDir.'/'.trim($language->getShortcut()).'/'.$k.'.php';
			
			if (!file_exists($fileName)){
				$file = fopen($fileName, "w+");
				fclose($file);
			}
			
			ob_start();
			echo "<?php return array( \n";
			$i = 1;
			foreach ($v as $key => $value){
				echo "\t".'"'.$value['translation'].'" => "'.$value['lt_translation'].'"';
				if($i < sizeof($v))
					echo ',';
				echo "\n";
				$i++;
			}
		
			echo '); ?>';
			$content = ob_get_contents();
		    ob_end_clean();
	    
		    file_put_contents($fileName, $content);
		}
		
		$msg = "Files creation success";
		echo $msg;
		exit();
		//$this->view->sTranslations = $sTranslations;
		//$smarty = $this->view->getEngine();

		//$tpl = $smarty->fetch('locale/generate-translations.tpl');
		
	}
}

	
?>
